<template>
  <div class="user-management">
    <div class="header">
      <h2>用户管理</h2>
      <el-button type="primary" @click="handleAddUser">
        新增用户
      </el-button>
    </div>

    <el-table :data="users" style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="role" label="角色">
        <template #default="{ row }">
          <el-tag :type="getRoleType(row.role)">
            {{ getRoleLabel(row.role) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="注册时间" />
      <el-table-column label="操作" width="250">
        <template #default="{ row }">
          <el-button-group>
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button 
              size="small" 
              type="warning" 
              @click="handleResetPassword(row)"
            >重置密码</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(row)"
            >删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      v-model="dialogVisible"
      :title="editingUser ? '编辑用户' : '新增用户'"
      width="50%"
    >
      <el-form :model="userForm" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="userForm.username" :disabled="!!editingUser" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="userForm.role">
            <el-option label="普通用户" value="user" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
        <el-form-item label="密码" v-if="!editingUser">
          <el-input v-model="userForm.password" type="password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUser">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const users = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const editingUser = ref(null)
const userForm = ref({
  username: '',
  email: '',
  role: 'user',
  password: ''
})

const fetchUsers = async () => {
  loading.value = true
  try {
    const response = await axios.get('/api/admin/users/')
    users.value = response.data
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

const handleAddUser = () => {
  editingUser.value = null
  userForm.value = {
    username: '',
    email: '',
    role: 'user',
    password: ''
  }
  dialogVisible.value = true
}

const handleEdit = (user) => {
  editingUser.value = user
  userForm.value = { ...user }
  delete userForm.value.password
  dialogVisible.value = true
}

const handleDelete = async (user) => {
  try {
    await ElMessageBox.confirm('确定要删除这个用户吗？', '警告', {
      type: 'warning'
    })
    await axios.delete(`/api/admin/users/${user.id}/`)
    ElMessage.success('删除成功')
    fetchUsers()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleResetPassword = async (user) => {
  try {
    const { value: password } = await ElMessageBox.prompt('请输入新密码', '重置密码', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputType: 'password'
    })
    
    await axios.post(`/api/admin/users/${user.id}/reset-password/`, {
      password
    })
    ElMessage.success('密码重置成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('密码重置失败')
    }
  }
}

const saveUser = async () => {
  try {
    if (editingUser.value) {
      await axios.put(`/api/admin/users/${editingUser.value.id}/`, userForm.value)
    } else {
      await axios.post('/api/admin/users/', userForm.value)
    }
    ElMessage.success(editingUser.value ? '更新成功' : '创建成功')
    dialogVisible.value = false
    fetchUsers()
  } catch (error) {
    ElMessage.error(editingUser.value ? '更新失败' : '创建失败')
  }
}

const getRoleType = (role) => {
  const types = {
    admin: 'danger',
    user: 'success'
  }
  return types[role] || 'info'
}

const getRoleLabel = (role) => {
  const labels = {
    admin: '管理员',
    user: '普通用户'
  }
  return labels[role] || role
}

onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
}
</style>
